package com.panshi.controller.usercenter;

import com.panshi.api.*;
import com.panshi.utils.GetSessionUser;
import com.panshi.utils.MailUtils;
import com.panshi.utils.RedisUtils;
import com.panshi.vo.ResponseVO;
import com.panshi.vo.UserVO;
import com.panshi.vo.qa.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserCenterController {//用户个人中心
    @Autowired
    private UserGetApi userGetApi; //用户APi类

    @Autowired
    private IQuestionApi questionApi; //问题api类

    @Autowired
    private IQuestionAuditApi questionAuditApi; //问题审核api

    @Autowired
    private IReplyAuditApi replyAuditApi; //问答审核api类

    @Autowired
    private IReplyApi replyApi; //问答api类

    @Autowired
    private IMessagApi messagApi; //站内消息api

    @Autowired
    RedisUtils redisUtils; //redis工具类

    @RequestMapping("/user_page/userindex")//用户个人中心页面
    public String userindex(Model model,HttpSession session){

        String uid = GetSessionUser.getSessionUserId()+"";
        System.out.println("userindex====="+uid);
        if(uid != null && uid != ""){
            //存入model里
            model.addAttribute("loginUser",GetSessionUser.getSessionUser());
            //查询问答数据存入model中
            getUserAllmsg(model);
            return "user_page/userindex";
        }else{
            //session里没有就返回登录页
            return "login";
        }
    }
    @RequestMapping("/user_page/userinfo")//用户个人信息页面
    public String userinfo(Model model){

        String uid = GetSessionUser.getSessionUserId()+"";
        System.out.println("userinfo====="+uid);
        if(uid != null && uid != ""){
            //存入model里
            model.addAttribute("loginUser",GetSessionUser.getSessionUser());
            //查询站内信息
            getUserMsgInfo(model);

            return "user_page/userinfo";
        }else{
            //session里没有就返回首页
            return "login";
        }
    }
    @RequestMapping("/user_page/usermsg")//用户站内消息页面
    public String usermsg(Model model,HttpSession session){

        String uid = GetSessionUser.getSessionUserId()+"";
        System.out.println("usermsg====="+uid);
        if(uid != null && uid != ""){
            //存入model里
            model.addAttribute("loginUser",GetSessionUser.getSessionUser());
            //查询站内消息
            getUserMsgInfo(model);

            return "user_page/usermsg";
        }else{
            //session里没有就返回登录页
            return "login";
        }
    }
    /**
     * 修改用户信息
     * @param nick 昵称
     * @param userDesc  个信签名
     * @param logo  图片
     * @return
     */
    @RequestMapping("/user_page/updateUserInfo")
    @ResponseBody
    public ResponseVO updateUser(HttpSession session,Model model,@RequestParam String nick,@RequestParam String userDesc,@RequestParam String logo){
        String uid = GetSessionUser.getSessionUserId()+"";
        System.out.println("updateUserInfo====="+uid);
        //修改用户
        UserVO newUserInfo = userGetApi.updateUserInfo(uid,nick,userDesc,logo);
        //将更新的值存入session
        session.setAttribute("loginUser",newUserInfo);
        //重新存入model
        model.addAttribute("loginUser",newUserInfo);
        ResponseVO rs=  new ResponseVO();
        rs.setSuccess(true);
        rs.setMsg("用户修改成功！");
        rs.setState(200);

        return rs;
    }
    /**
     * 修改用户密码
     * @param model 当前视图模板
     * @param pwd   新密码
     * @param pwdOld    旧密码
     * @return
     */
    @RequestMapping("/user_page/update/updatePwd")
    @ResponseBody
    public ResponseVO updateUserPwd(HttpSession session,Model model, @RequestParam String pwd, @RequestParam String pwdOld){
        String uid = GetSessionUser.getSessionUserId()+"";
        System.out.println("updatePwd====="+uid);
        //拿到原密码
        String loginpwd = GetSessionUser.getSessionUser().getU_password();
        ResponseVO rs = new ResponseVO();
        //原密码正确
        if(pwdOld.equals(loginpwd)){
            rs = userGetApi.updateUserPwd(uid,pwd);
            UserVO newLoginUser = userGetApi.findUserByUid(uid);
            //重新存入session
            session.setAttribute("loginUser",newLoginUser);
            //重新存入model
            model.addAttribute("loginUser",newLoginUser);
            return rs;
        }else{
            rs.setSuccess(false);
            rs.setState(500);
            rs.setMsg("旧密码输入错误！");
            return rs;
        }
    }
    /**
     * 修改邮箱
     * @param uid 修改的用户
     * @param newMail   新邮箱
     * @return
     */
    @RequestMapping("/user_page/update/updateEmail")
    @ResponseBody
    public ResponseVO updateUserEmail(@RequestParam String uid , @RequestParam String newMail){

        return userGetApi.updateUserEmail(uid,newMail);
    }
    /**
     * @param newEmail 新邮箱
     * @return
     */
    @RequestMapping("/user_page/update/sendCode/email")
    @ResponseBody
    public ResponseVO sendEmail(@RequestParam String newEmail){
        Jedis jedis = RedisUtils.getJedis();
        String type = "update";
        String uid = GetSessionUser.getSessionUserId()+"";
        System.out.println("email====="+uid);
        //发送邮箱验证码
        String sendCode = MailUtils.createSimpleMail();
        //发送内容
        String content = "【有贝口腔网】验证码为："+sendCode+" ( 切勿将验证码告知他人 ),请在页面中输入完成验证，如有问题，请联系有贝口腔网客服。";
        try {
            MailUtils.sendMail(newEmail, "有贝口腔网注册验证", content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将邮箱验证码存入redis中
        //NX Key不存在时才set EX是秒 PX是毫秒 300是key的有效期5分钟
        jedis.set(type+":"+newEmail,sendCode,"NX","EX",300);
        ResponseVO rs = new ResponseVO();
        rs.setSuccess(true);
        rs.setState(200);
        rs.setMsg("验证码发送成功！请注意查收");
        return rs;
    }

    /**
     * 验证邮箱验证码是否正确
     * @param checkcode 输入的验证码
     * @return
     */
    @RequestMapping("/user_page/update/confirm/email")
    @ResponseBody
    public ResponseVO confirmEmail(@RequestParam String newEmail,@RequestParam String checkcode){
        String type = "update";
        System.out.println("newEmail====:"+newEmail);
        System.out.println("checkcode====:"+checkcode);
        //从redis里面拿到刚才发送的验证码
        Jedis jedis = redisUtils.getJedis();
        //从session里面拿到用户id
        String uid = GetSessionUser.getSessionUserId()+"";
        //获取redis里储存的邮箱验证码
        String emailCode = jedis.get(type+":"+newEmail);

        ResponseVO rs = new ResponseVO();
        if(checkcode.equals(emailCode)){
            userGetApi.updateUserEmail(uid,newEmail);
            rs.setState(200);
            rs.setMsg("邮箱验证成功！邮箱已修改");
            rs.setSuccess(true);
        }else {
            rs.setSuccess(false);
            rs.setMsg("邮箱验证码输入错误！邮箱修改失败");
            rs.setState(500);
        }
        return rs;
    }

    /**
     *向新邮箱发送验证码
     * @param userName 新邮箱地址
     * @return
     */
    @RequestMapping("/user_page/update/new_sendCode/email")
    @ResponseBody
    public ResponseVO newSendEmail(String userName){
        String type = "update";
        Jedis jedis = redisUtils.getJedis();
        //发送邮箱验证码
        String sendCode = MailUtils.createSimpleMail();
        //发送内容
        String content = "【有贝口腔网】验证码为："+sendCode+" ( 切勿将验证码告知他人 ),请在页面中输入完成验证，如有问题，请联系有贝口腔网客服。";
        try {
            MailUtils.sendMail(userName, "有贝口腔网注册验证", content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将邮箱验证码存入redis中
        //NX Key不存在时才set EX是秒 PX是毫秒 300是key的有效期5分钟
        jedis.set(type+":"+userName,sendCode,"NX","EX",300);
        ResponseVO rs = new ResponseVO();
        rs.setSuccess(true);
        rs.setState(200);
        rs.setMsg("验证码发送成功！请注意查收");
        return rs;
    }

    /**
     * 查询站内消息
     * @param model
     */
    public void getUserMsgInfo(Model model){
        //从session里面拿到用户id
        int uid = GetSessionUser.getSessionUserId();
        System.out.println("selectQA=======uid"+uid);
        //分页属性类
        Pages pages = new Pages();
        //分页大小
        pages.setPageSize(5);
        //分页起始页
        pages.setStartPage(1);
        //用户id
        pages.setUserId(uid);

        List<Messag> msgList = messagApi.inquirePagesMessag(pages).getData();
        //该用户的提问总数
        DataResultQA<Pages<Question>> datas = questionApi.inquirePagesQuestion(pages);
        int questionCount = datas.getData().getSum();
        //查出该用户回答问题的总数
        System.out.println(pages);
        int answerCount = replyApi.inquireReplySum(pages).getData();
        //获取该用户的站内消息数量
        int mesgCount =messagApi.inquireSum(uid).getData();

        model.addAttribute("questionCount",questionCount);
        model.addAttribute("answerCount",answerCount);
        model.addAttribute("mesgCount",mesgCount);
        System.out.println("msgList====="+msgList);
        model.addAttribute("msgList",msgList);
    };

    /**
     * 查询主页动态
     * @param model
     */
    public void getUserAllmsg(Model model){

        System.out.println("查询主页动态");
        //从session里面拿到用户id
        int uid = GetSessionUser.getSessionUserId();
        System.out.println("selectQA=======uid"+uid);
        //分页属性类
        Pages pages = new Pages();
        //分页大小
        pages.setPageSize(5);
        //分页起始页
        pages.setStartPage(1);
        //用户id
        pages.setUserId(uid);
        //调用问答api类查询
        //DataResultQA<Pages<Question>> datas = qaApi.inquireMyPagesQuestion(pages);
        DataResultQA<Pages<Question>> datas = questionApi.inquirePagesQuestion(pages);
        //该用户的问题集合
        List<Question> qalist = datas.getData().getList();
        //该用户的提问总数
        int questionCount = datas.getData().getSum();
        //查出该用户回答问题的总数
        System.out.println(pages);
        int answerCount = replyApi.inquireReplySum(pages).getData();
        System.out.println("answerCount===="+answerCount);
        //存入视图模板中
        model.addAttribute("qalist",qalist);
        model.addAttribute("questionCount",questionCount);
        model.addAttribute("answerCount",answerCount);
        //获取该用户的站内消息数量
        int mesgCount =messagApi.inquireSum(uid).getData();
        model.addAttribute("mesgCount",mesgCount);
        System.out.println("model中的qalist"+model.getAttribute("qalist"));
        System.out.println( "model"+model);
    }
}
